package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/5/17 10:20
 * @Version 1.0
 */
@Controller
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    //  访问首页控制器
    @GetMapping({"/","index.html"})
    public String index(Model model){
        //  获取远程调用
        Result result = productFeignClient.getBaseCategoryList();
        //  存储数据
        model.addAttribute("list",result.getData());
        //  首页页面
        return "index/index";
    }

    //  生成一个静态化页面。
    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex(){
        //  获取远程调用
        Result result = productFeignClient.getBaseCategoryList();

        //  创建一个Context 对象
        Context context = new Context();
        //  name 指页面渲染的key，value=渲染数据
        context.setVariable("list",result.getData());
        //  创建一个Writer 对象
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("D:\\index.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        templateEngine.process("index/index.html",context,fileWriter);
        return Result.ok();
    }
}
